package com.example.demo.service.impl;

import com.example.demo.dao.BalanceRepository;
import com.example.demo.model.entity.BalanceModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class BalanceService {

    @Resource
    BalanceRepository balanceRepository;

    @Resource
    JdbcTemplate jdbcTemplate;

    public Page<BalanceModel> getBalancePage(Specification specification, Pageable pageable) {
        return balanceRepository.findAll(specification, pageable);
    }

    public List<BalanceModel> getBalanceAll(Specification specification) {
        return balanceRepository.findAll(specification);
    }

    public void save(BalanceModel model) {
        balanceRepository.save(model);
    }

    public Double sum(String start, String end, String balanceType) {
        String sql = "SELECT SUM(balance) FROM t_balance WHERE 1 = 1";
        List<Object> params = new ArrayList<>();


        if (StringUtils.isNotEmpty(start)) {
            sql += " AND create_time >= ?";
            params.add(start);
        }
        if (StringUtils.isNotEmpty(end)) {
            sql += " AND create_time <= ?";
            params.add(end);
        }
        if (StringUtils.isNotEmpty(balanceType)) {
            sql += " AND balance_desc = ?";
            params.add(balanceType);
        }

        return jdbcTemplate.queryForObject(sql, params.toArray(), Double.class);


    }


}
